package com.kgc.crowd.ossdemo.controller;

import com.kgc.crowd.ossdemo.config.OSSProperties;
import com.kgc.crowd.ossdemo.utils.AliyunOSSUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Controller
public class OssController {

    @RequestMapping("/toupload")
    public String toupload(){
        return "upload";
    }

    @RequestMapping("/upload")
    public String upload(@RequestParam("projectheadpic") MultipartFile projectheadpic, Model model){
        System.out.println("jinggiehowehgweoigh");
        if (projectheadpic!=null){
            //获取文件名
            String filename = projectheadpic.getOriginalFilename();
            //把文件变成文件流
            InputStream inputStream=null;
            try {
                inputStream = projectheadpic.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                //调用文件上传方法
                String upload = AliyunOSSUtil.upload(inputStream, filename);
                model.addAttribute("imgURL","https://"+ OSSProperties.BUCKET_NAME+"."+OSSProperties.ENDPOINT+"/"+upload);
                model.addAttribute("msg","文件上传成功");
                return "upload";
            }catch (Exception ex){
                ex.printStackTrace();
                model.addAttribute("msg",ex.getMessage());
                return "upload";
            }

        }else{
            model.addAttribute("msg","请选择文件");
            return "upload";
        }
    }
}
